package com.mdp.workflow.ru.listener.global;

import com.alibaba.fastjson.JSONObject;
import com.mdp.core.entity.Tips;
import com.mdp.core.err.BizException;
import com.mdp.core.utils.ObjectTools;
import com.mdp.form.FormUtil;
import com.mdp.micro.client.CallBizService;
import com.mdp.workflow.ru.entity.ProcinstNodeInfo;
import com.mdp.workflow.ru.listener.PushImMsgService;
import com.mdp.workflow.ru.service.ProcinstNodeInfoService;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.flowable.bpmn.model.FlowElement;
import org.flowable.bpmn.model.UserTask;
import org.flowable.common.engine.api.delegate.event.FlowableEvent;
import org.flowable.common.engine.api.delegate.event.FlowableEventListener;
import org.flowable.common.engine.impl.interceptor.CommandContext;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.event.impl.FlowableEntityEventImpl;
import org.flowable.engine.delegate.event.impl.FlowableEntityWithVariablesEventImpl;
import org.flowable.engine.impl.util.CommandContextUtil;
import org.flowable.task.service.impl.persistence.entity.TaskEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;


/**
 * 任务节点前置监听处理类
 * @author: Lu Yang
 * @create: 2019-05-04 20:51
 **/
@Component
public class TaskCompletedListener implements FlowableEventListener {

	Log log=LogFactory.getLog(TaskCompletedListener.class);

	@Value(value = "${mdp.form.data-approva-uri:/lcode/formData/processApprova}")
	String formDataApprovaUri="";

	@Autowired
	CallBizService callBizService;
	
	@Autowired
    PushImMsgService pushMsgService;
	

	@Autowired
	private ProcinstNodeInfoService procinstNodeInfoService;
	
	
	 public DelegateExecution getExecution(String executionId) {
	        if (executionId != null) {
	            CommandContext commandContext = CommandContextUtil.getCommandContext();
	            if (commandContext != null) {
	                return CommandContextUtil.getExecutionEntityManager(commandContext).findById(executionId);
	            }
	        }
	        return null;
	    }
	

    @Override
    public void onEvent(FlowableEvent event) {
		// TODO Auto-generated method stub
		 // 当前节点任务实体
    	FlowableEntityEventImpl eventImpl;
    	if(event instanceof FlowableEntityWithVariablesEventImpl) {
    		eventImpl=(FlowableEntityWithVariablesEventImpl)event;
    	}else {
    		eventImpl=(FlowableEntityEventImpl)event;
    	} 
       TaskEntity taskEntity = (TaskEntity) (eventImpl).getEntity();
       
       //taskEntity.getVariable("nrOfDisAgree");
       DelegateExecution execution=this.getExecution(eventImpl.getExecutionId());
		String procDefId=execution.getProcessDefinitionId();
		FlowElement element=execution.getCurrentFlowElement();
		if(element instanceof UserTask) {
		if(execution.hasVariable("assigneeList")) {
				//execution.removeVariable("assigneeList");
			}
			if(execution.hasVariable("assignee")) {
				//execution.removeVariable("assignee");
			}
		UserTask task=(UserTask)element;
			if(task.hasMultiInstanceLoopCharacteristics()){
				/**
				 * 另附判断结果类中流程引擎自带可用变量：
					1.nrOfInstances 该会签环节中总共有多少个实例
						2.nrOfActiveInstances 当前活动的实例的数量，即还没有 完成的实例数量。
						3.nrOfCompletedInstances 已经完成的实例的数量
						4.nrOfAgree 同意个数
						5.nrOfDisAgree 不同意个数
					 */
				int completedInstance = (int)execution.getVariable("nrOfCompletedInstances");
				log.debug("completedInstance"+completedInstance);
				int nrOfDisAgree= (int) taskEntity.getVariable("nrOfDisAgree");
				int nrOfAgree= (int) taskEntity.getVariable("nrOfAgree"); 
				String agree=(String) taskEntity.getVariable("agree"); 
				if("1".equals(agree)) {
					nrOfAgree=nrOfAgree+1;
					taskEntity.setVariable("nrOfAgree", nrOfAgree);
				}else if("0".equals(agree)) {
					nrOfDisAgree=nrOfDisAgree+1;
					taskEntity.setVariable("nrOfDisAgree", nrOfDisAgree);
				}
				return;
			}else {//普通的单人人工任务节点
				//subscribeTaskEvent
				//如果有上送restUrl，回调restUrl推送审核数据
				Map<String,Object> flowVars=execution.getVariables();
	            String restUrl=(String) flowVars.get("restUrl"); 
                String mainTitle=(String) flowVars.get("mainTitle");
                String subscribeTaskEvent=(String) flowVars.get("subscribeTaskEvent");
                String currentUserid=(String) flowVars.get("currentUserid");
                String currentUsername=(String) flowVars.get("currentUsername");
                String startUserid=(String) flowVars.get("startUserid");
                String taskName=taskEntity.getName();
				String formId=(String) flowVars.get("formId");
	            if(ObjectTools.isNotEmpty(formId) || (!StringUtils.isEmpty(restUrl) && subscribeTaskEvent!=null && subscribeTaskEvent.contains(event.getType().name()))) {
	            	Map<String, Object> paramMap = new HashMap<String, Object>();
	                
	                ///processInstance.get
	                String bizKey=(String) flowVars.get("bizKey");
	                String processInstanceId=taskEntity.getProcessInstanceId(); 
	                String actId=taskEntity.getTaskDefinitionKey();
	                
	                String branchId=taskEntity.getTenantId();
	                String eventName=event.getType().name();

	                paramMap.putAll(flowVars);
	                paramMap.put("procInstId", processInstanceId);
	                paramMap.put("startUserid", startUserid);
	                paramMap.put("mainTitle", mainTitle);
	                paramMap.put("assignee", currentUserid);
	                paramMap.put("assigneeName", currentUsername);

	                paramMap.put("actId", actId);
	                paramMap.put("taskName", taskName);
	                paramMap.put("flowBranchId", branchId); 
	                paramMap.put("bizKey", bizKey);
	                paramMap.put("eventName", eventName); 
	                paramMap.put("modelKey", execution.getProcessDefinitionId());
					Tips tips = new Tips();
	                if(!StringUtils.isEmpty(formId)) {   
	                	paramMap.put("formId", formId);
	                	ProcinstNodeInfo node=procinstNodeInfoService.getNodeInfoFromCache(processInstanceId, actId);
	                	String fieldIds=null;
	                	if(node!=null && !StringUtils.isEmpty(node.getFormFieldsJson())) {
	                		String formFieldJson=node.getFormFieldsJson();
	                		JSONObject formFieldsObj= JSONObject.parseObject(formFieldJson);
							fieldIds=formFieldsObj.getString("edit");
	                	}
	                	paramMap.put(FormUtil.NEED_UPDATE_FORM_DATA_FIELD_ID_LIST, fieldIds);
	                	if(restUrl.indexOf(formDataApprovaUri)>=0) {
	                		tips=callBizService.postForTips(restUrl, paramMap);
	                	}else {
	                		tips=callBizService.postForTips(formDataApprovaUri, paramMap);
	                		tips=callBizService.postForTips(restUrl, paramMap);
	                	}
	                	
		            }else {
		            	tips=callBizService.postForTips(restUrl, paramMap);
		            }  
	            	if(tips.isOk()==false) {
	            		throw new BizException(tips);
	            	}
	            }
	            pushMsgService.pushMsgToIm(startUserid, "流程【"+mainTitle+"】,任务【"+taskName+"】已由【"+currentUsername+"】提交");
			}
		} 

		
	}

    @Override
    public boolean isFailOnException() {
        return true;
    }

    @Override
    public boolean isFireOnTransactionLifecycleEvent() {
        return false;
    }

    @Override
    public String getOnTransaction() {
        return null;
    }
}